package com.zhu.rpc.server;

import java.util.*;

//保存返回消息，用于消息返回失败，不会重复调用接口
public class ResponseMessageCache {
    //最大清除数
    private static int maxClearSize = 1024;
    //基本保留数
    private static int containBase = 32;
    //过期时间 毫秒
    private static int overtime = 30*1000;
    private static HashMap<String,RespMsg> responseMessageMap = new HashMap<>(maxClearSize +100);
    private static LinkedList<String> list = new LinkedList<>();

    public synchronized static void cacheResponseMsg(String msgId, String message){
        list.add(msgId);
        responseMessageMap.put(msgId,new RespMsg(System.currentTimeMillis(),message));
        if (list.size()>= maxClearSize){
            //过期任务移出
            long currentTime;
            long thisTime;
            int removeCount=0 ;
            for (int i = 0; i < 6; i++) {
                removeCount = maxClearSize - containBase<<i;
                thisTime= responseMessageMap.get(list.get(removeCount)).time;
                currentTime = System.currentTimeMillis();
                if ((currentTime-thisTime)> overtime){
                    //表示队列中的这个位置的数据已过期需要清除
                    break;
                }
            }
            for (int i = 0; i < removeCount; i++) {
                responseMessageMap.remove(list.removeFirst());
            }
        }
    }

    public static String getResponse(String msgId){
        RespMsg respMsg = responseMessageMap.get(msgId);
        return respMsg == null?null:respMsg.msg;
    }

    private static class RespMsg{
        public long time;
        public String msg;

        public RespMsg(long time, String msg) {
            this.time = time;
            this.msg = msg;
        }
    }
}
